package cn.text.ico;

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

public class Text implements Runnable {

    @Override
    public void run() {
        String path = WelcomeInterface.path.getText().replace('\\', '/');
        File file = new File(path + "/ico");
        file.mkdir();
        CloseableHttpClient httpClient1 = HttpClients.createDefault();
        CloseableHttpResponse response1 = null;
        int i = 1;
        try {
            for (; i <= Integer.parseInt(WelcomeInterface.page.getText()); i++) {
                HttpGet request1 = new HttpGet(
                        "https://www.logosc.cn/logo?keywords=" + WelcomeInterface.number.getText() + "&page=" + i);
                try {
                    response1 = httpClient1.execute(request1);
                    if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        HttpEntity httpEntity1 = response1.getEntity();
                        String html1 = EntityUtils.toString(httpEntity1, "gb2312");
                        org.jsoup.nodes.Document document1 = Jsoup.parse(html1);
                        Elements elements = document1.select("div.grid  div.relative div.flex > img");
                        System.out.println(elements);
                        for (int j = 0; j < 20; j++) {
                            String src = elements.get(j).attr("src");
                            if (src.contains("png")) {
                                PicDown.Down("https://www.logosc.cn/" + src, elements.get(j).attr("alt"));
                            }
                        }
                    } else {
                        WelcomeInterface.log.append("404!");
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    break;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            WelcomeInterface.log.append("下载失败！请检查网络或下载新版本！");
        }
        WelcomeInterface.log.append("一共下载  " + --i + "  页  " + PicDown.count + "  个图标");
        WelcomeInterface.start.setSelected(true);
        WelcomeInterface.number.setEditable(true);
        WelcomeInterface.page.setEditable(true);
        WelcomeInterface.thread.stop();
    }
}